package com.cloud.redis.utils;

import org.redisson.Redisson;
import org.redisson.api.*;
import org.redisson.config.Config;

import java.util.concurrent.TimeUnit;

public class RedissonUtil {
    private static RedissonClient redisson;

    // 初始化 Redisson 客户端
    public static void init(String redisAddress) {
        if (redisson == null) {
            Config config = new Config();
            config.useSingleServer().setAddress(redisAddress);
            // 也可以配置集群模式、哨兵模式等，根据需求选择
            redisson = Redisson.create(config);
        }
    }

    // 获取 Redisson 客户端
    public static RedissonClient getRedisson() {
        return redisson;
    }

    // 销毁 Redisson 客户端
    public static void shutdown() {
        if (redisson != null) {
            redisson.shutdown();
        }
    }

    // 操作 String 类型数据
    public static void setString(String key, String value) {
        RBucket<String> bucket = redisson.getBucket(key);
        bucket.set(value);
    }

    public static String getString(String key) {
        RBucket<String> bucket = redisson.getBucket(key);
        return bucket.get();
    }

    // 操作 Hash 类型数据
    public static void setHash(String hashKey, String key, String value) {
        RMap<String, String> map = redisson.getMap(hashKey);
        map.put(key, value);
    }

    public static String getHash(String hashKey, String key) {
        RMap<String, String> map = redisson.getMap(hashKey);
        return map.get(key);
    }

    // 操作 List 类型数据
    public static void addToList(String listKey, String value) {
        RList<String> list = redisson.getList(listKey);
        list.add(value);
    }

    public static String getFromList(String listKey, int index) {
        RList<String> list = redisson.getList(listKey);
        return list.get(index);
    }

    // 操作 Set 类型数据
    public static void addToSet(String setKey, String value) {
        RSet<String> set = redisson.getSet(setKey);
        set.add(value);
    }

    public static boolean isMemberOfSet(String setKey, String value) {
        RSet<String> set = redisson.getSet(setKey);
        return set.contains(value);
    }

    // 操作 Lock（分布式锁）
    public static void lock(String lockKey) throws InterruptedException {
        RLock lock = redisson.getLock(lockKey);
        lock.lock(10, TimeUnit.SECONDS); // 锁定 10 秒
    }

    public static void unlock(String lockKey) {
        RLock lock = redisson.getLock(lockKey);
        lock.unlock();
    }

    // 操作 AtomicLong（原子增量）
    public static long incrementAtomicLong(String key) {
        RAtomicLong atomicLong = redisson.getAtomicLong(key);
        return atomicLong.incrementAndGet();
    }
}
